﻿using RndMaterialDisposalService.Attrbutes;
using Coravel;
using System.Reflection;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class CoravelJobExtensions
    {



        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        public static void AddCoravelJob(this IServiceCollection builder)
        {
            builder.AddScheduler();
            var types = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.GetCustomAttribute<CoravelJobAttribute>() != null);
            foreach (var item in types)
            {
                builder.AddTransient(item);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static WebApplication UseCoravelJob(this WebApplication app)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.GetCustomAttribute<CoravelJobAttribute>() != null);

            app.Services.UseScheduler(scheduler =>
            {
                foreach (var item in types)
                {
                    var job = item.GetCustomAttribute<CoravelJobAttribute>();
                    scheduler.ScheduleInvocableType(item).Cron(job!.Cron);
                    Console.WriteLine($"Inject Coravel Job: {item.Namespace},Cron:{job!.Cron}");
                }
            });

            return app;
        }

    }
}
